package com.btpj.module_tree_details.ui

import androidx.lifecycle.viewModelScope
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import com.btpj.jetpack.base.BaseListViewModel
import com.btpj.jetpack.entity.DataBean
import com.btpj.jetpack.utils.ToastUtil
import com.btpj.jetpack.entity.ApiResult
import com.btpj.module_tree_details.data.remote.TreeDetailRepository
import kotlinx.coroutines.launch
import java.util.*

class TreeDetailViewModel(private val repository: TreeDetailRepository) :
    BaseListViewModel<DataBean>() {

    var treeId = 0

    override fun createDataSource(): DataSource<Int, DataBean> {
        return object : PageKeyedDataSource<Int, DataBean>() {
            override fun loadInitial(
                params: LoadInitialParams<Int>,
                callback: LoadInitialCallback<Int, DataBean>
            ) {
                loadData(0, callback)
            }

            override fun loadAfter(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, DataBean>
            ) {
                loadData(params.key, callback)
            }

            override fun loadBefore(
                params: LoadParams<Int>,
                callback: LoadCallback<Int, DataBean>
            ) {
                callback.onResult(Collections.emptyList(), null)
            }
        }
    }

    private fun loadData(
        key: Int,
        callback: PageKeyedDataSource.LoadInitialCallback<Int, DataBean>
    ) {
        viewModelScope.launch {
            when (val result = repository.getTreeDetailList(key, treeId)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, null, 1)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "请求失败")
            }
        }
    }

    private fun loadData(
        key: Int,
        callback: PageKeyedDataSource.LoadCallback<Int, DataBean>
    ) {
        viewModelScope.launch {
            when (val result = repository.getTreeDetailList(key, treeId)) {
                is ApiResult.Success -> callback.onResult(result.data.datas, key + 1)
                is ApiResult.Error -> ToastUtil.showShort(result.exception.errorMsg ?: "请求失败")
            }
        }
    }
}